/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

package utfpr.cp.model;

import edu.uci.ics.crawler4j.url.WebURL;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.Query;
import semanticrawler.Main;

/**
 *
 * @author Adriano_2
 */
public class URLDataDAO extends DAO {

    public URLDataDAO(EntityManager em) {
        super(em);
    }
    
    public URLData getOrCreate(WebURL url) {
        em.getTransaction().begin();
        URLData myURL = getByUrl(url.getURL());
        if (!myURL.exist()) {
              myURL =  new URLData(url);
              if (!save(myURL, em)) {
                  Logger.getLogger(Main.class.getName()).log(Level.INFO, "Falha ao criar a url: ["+myURL.getUrl()+"]");
              }
        }
        em.getTransaction().commit();
        return myURL;
    }
    
    public URLData getByUrl(String uri) {
        Query q = em.createQuery("SELECT e FROM URLData e WHERE url = :url");
        q.setParameter("url", uri);
        try {
            return (URLData) q.getSingleResult();
        } catch (NoResultException e) {
            //Logger.getLogger(Main.class.getName()).log(Level.SEVERE, null, e);
            return new URLData(uri);
        }
    }
    
    public long getTotalURL() {
         try {
            Query q = em.createQuery("SELECT count(u) FROM URLData u");
            return ((Long) q.getSingleResult() ).longValue();
        }
        catch (Exception e) {
            return -1;
        }
    }
    
    public static URLDataDAO factory() {
        return new URLDataDAO(getEntity());
    }
}
